<template>
  <div class="area">
    <ContentWrap>
      <el-form
        ref="formRef"
        :rules="rules"
        :inline="true"
        :model="ruleForm"
        class="demo-form-inline search"
      >
        <el-form-item>
          <el-button @click="handleAdd('add')" :icon="Plus" plain type="primary">添加</el-button>
        </el-form-item>
        <el-form-item style="float: right; margin-right: 0">
          <el-button
            type="primary"
            :icon="DataAnalysis"
            tag="a"
            href="http://10.101.221.209:7474/browser/"
            target="_blank"
          >
            图数据库
          </el-button>
          <el-button @click="handleLog" :icon="Grid" plain type="info">图谱日志</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div style="height: 560px">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2
              :columns="columns"
              :data="tableModule.tableData"
              :width="width"
              :height="height"
              fixed
            />
          </template>
        </el-auto-resizer>
      </div>
      <el-pagination
        :current-page="tableModule.currentPage"
        :page-size="tableModule.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :small="false"
        :disabled="false"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableModule.count"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </ContentWrap>
  </div>
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="800px" draggable align-center>
    <el-form
      ref="ruleFormRef"
      :rules="formRules"
      :model="formData"
      label-position="right"
      label-width="auto"
    >
      <el-form-item label="知识库名称" :label-width="formLabelWidth" prop="graphName">
        <el-input
          v-model="formData.graphName"
          placeholder="请输入知识库名称"
          :disabled="handleState === 'edit' ? true : false"
        />
      </el-form-item>
      <el-form-item label="知识库类型" :label-width="formLabelWidth" prop="graphType">
        <el-select
          v-model="formData.graphType"
          style="width: 100%"
          placeholder="请选择知识库类型"
          clearable
          :disabled="handleState === 'edit' ? true : false"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="知识库简介" :label-width="formLabelWidth" prop="graphIntro">
        <el-input
          v-model="formData.graphIntro"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 4 }"
          resize="none"
          clearable
          placeholder="请输入知识库简介"
        />
      </el-form-item>
      <!-- <el-form-item v-show="formData.graphType === '图谱知识库'" label="单选" :label-width="formLabelWidth" prop="">
        <el-radio-group v-model="formData.radio" class="ml-4">
          <el-radio label="1">图书资源</el-radio>
          <el-radio label="2">导入无结构数据文件</el-radio>
          <el-radio label="3">excel文件</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item
        v-show="formData.graphType === '图谱知识库'"
        label="图书资源"
        :label-width="formLabelWidth"
        prop="name4"
      >
        <el-button type="primary" @click="bookAdd" :disabled="handleState === 'edit' ? true : false"
          >添加</el-button
        >
      </el-form-item>
      <el-form-item
        v-show="formData.graphType === '图谱知识库' && formData.radio === '2'"
        label="图书资源"
        :label-width="formLabelWidth"
        prop="name4"
      >
        <el-button @click="handleImport" :icon="Download" plain type="warning">导入</el-button>
      </el-form-item>
      <el-form-item
        v-show="formData.graphType === '图谱知识库' && formData.radio === '3'"
        label="图书资源"
        :label-width="formLabelWidth"
        prop="name4"
      >
        <el-button @click="handleImport" :icon="Download" plain type="warning">导入</el-button>
      </el-form-item>
      <el-form-item
        v-show="formData.graphType === '知识库'"
        label="导入模板"
        :label-width="formLabelWidth"
        prop="name4"
      >
        <el-button @click="handleImport" :icon="Download" plain type="warning">导入</el-button>
      </el-form-item>
      <div style="height: 300px" v-show="fatherBooksArray.length">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2
              :columns="columnsBooks"
              :data="fatherBooksArray"
              :width="width"
              :height="height"
            />
          </template>
        </el-auto-resizer>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submitForm(ruleFormRef)" type="primary" :auto-insert-space="true"
          >确定</el-button
        >
        <el-button @click="Cancel(ruleFormRef)" :auto-insert-space="true">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <importForm ref="importFormRef" :source="formData.radio" />
  <books ref="booksRef" @booksArray="handleBooksArray" />
  <graphLog ref="graphLogRef" dialogTitle="图谱日志" />
  <tableDialog
    ref="tableDialogRef"
    dialogTitle="图谱关系闭环验证"
    :operationalData="operationalData"
  ></tableDialog>
</template>
<script lang="tsx" setup>
import { useRouter, useRoute } from 'vue-router'
import { Plus, Upload, Download, Grid, DataAnalysis } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, Column } from 'element-plus'
import * as FormApi from '@/api/knowledge/area'
import dayjs from 'dayjs'
import importForm from './importForm.vue'
import books from './books.vue'
import graphLog from './graphLog.vue'
import tableDialog from './tableDialog.vue'
const tableDialogRef = ref()
const radio = ref(3)
const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const handleState = ref() // 输入框按钮是否可用
const ruleFormRef = ref<FormInstance>()
interface FormData {
  graphName: string
  graphType: string
  graphIntro: string
  radio: string
}
const importFormRef = ref()
const booksRef = ref()
const graphLogRef = ref()
// 添加弹窗表单
const formData = reactive<FormData>({
  graphName: '', // 图谱名称
  graphType: '', // 图谱类型
  graphIntro: '', // 图谱简介
  radio: '1'
})
const operationalData = reactive({})
const handleValidate = (data) => {
  Object.assign(operationalData, data.rowData)
  tableDialogRef.value.open()
}
const checkGraphName = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('知识库名称不能为空'))
  }
  setTimeout(() => {
    if (Number.isInteger(Number(value))) {
      callback(new Error('知识库名称不能为数字'))
    } else {
      if (value.length < 2) {
        callback(new Error('知识库名称必须两个字及以上'))
      } else {
        callback()
      }
    }
  }, 0)
}
const formRules = reactive({
  graphName: [{ required: true, validator: checkGraphName, trigger: 'blur' }],
  graphType: [{ required: true, message: '知识库类型不能为空', trigger: 'change' }],
  graphIntro: [{ required: true, message: '知识库简介不能为空', trigger: 'blur' }]
})
const rules = reactive<FormRules<RuleForm>>({
  region: [{ required: true, message: '请选择所属知识库', trigger: 'change' }],
  name: [{ required: true, message: '请输入节点名称', trigger: 'blur' }]
})
// 图谱类型
const options = [
  { label: '图谱知识库', value: '图谱知识库' },
  { label: '知识库', value: '知识库' }
]
interface RuleForm {
  name: string
  region: string
}
const ruleForm = reactive<RuleForm>({
  region: '',
  name: ''
})
let dialogTitle = ref<string>('')
let dialogFormVisible = ref(false)
const formLabelWidth = '100px'
// 弹窗操作类型
let operationType = ref<String>('')
// 表格数据
const tableModule = reactive({
  tableData: [], // 表格数据
  currentPage: 1, // 表格分页：当前页
  pageSize: 10, // 表格分页：每页显示条目个数
  count: 1 // 表格分页：总记录数
})
// 重置表单
const resetFormFcn = async (formData) => {
  Object.keys(formData).filter((item) => {
    delete formData[item]
  })
}
// 列表查询
const getTableData = async () => {
  const params = {
    pageNo: tableModule.currentPage,
    pageSize: tableModule.pageSize
  }
  FormApi.getGraphPage(params).then((res) => {
    tableModule.tableData = res.list
    tableModule.count = res.total
    dialogFormVisible.value = false
    // ElMessage({
    //   message: '查询成功',
    //   grouping: true,
    //   showClose: true,
    //   type: 'success'
    // })
  })
}
getTableData()
// 弹窗取消
const Cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
  fatherBooksArray.splice(0, fatherBooksArray.length)
}
const fatherBooksArray = reactive([]) // 图书资源选中数据弹窗回显
const handleBooksArray = (booksArray) => {
  Object.assign(fatherBooksArray, booksArray)
}
// 弹窗确定
const submitForm = async (formEl: FormInstance | undefined) => {
  let addReturnId = ''
  let addReturngraphName = formData.graphName
  const params = { ...formData }
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (operationType.value == 'add') {
        FormApi.insertHybaseGraph(params).then((res) => {
          addReturnId = res
          dialogFormVisible.value = false
          formEl.resetFields()
          ElMessage({
            message: '添加成功',
            grouping: true,
            showClose: true,
            type: 'success'
          })
          resetFormFcn(formData)
          getTableData()
          if (addReturnId) {
            const params = {
              // bookName: "xml",
              // bookUrl: "C:\\Users\\86187\\Desktop\\xml\\2_chapter_00001.xml",
              dataIds: fatherBooksArray.map((item) => item.id),
              graphName: addReturngraphName,
              graphId: addReturnId
            }
            FormApi.insertHybaseAndNeo4j(params).then((res) => {
              console.log(res)
            })
          }
        })
      } else if (operationType.value == 'edit') {
        FormApi.updateHybaseGraph(params).then((res) => {
          dialogFormVisible.value = false
          formEl.resetFields()
          ElMessage({
            message: '修改成功',
            grouping: true,
            showClose: true,
            type: 'success'
          })
          resetFormFcn(formData)
          getTableData()
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 修改
const edit = (type: string, data: any) => {
  handleState.value = 'edit'
  operationType.value = type
  dialogFormVisible.value = true
  dialogTitle.value = '修改知识库'
  console.log(data.rowData)
  Object.assign(formData, data.rowData)
  console.log(formData)
  // Object.keys(formData).forEach((item) => { formData.item = data.rowData.item })
}
// 删除
const deleteFcn = (data: any) => {
  ElMessageBox.confirm('确定永久删除该条数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      console.log(data.rowData.id)
      FormApi.deleteHybaseGraph(data.rowData.id)
        .then((res: any) => {
          ElMessage({
            type: 'success',
            grouping: true,
            showClose: true,
            message: '删除已完成'
          })
          getTableData()
        })
        .catch((error: any) => {
          ElMessage({
            message: error,
            grouping: true,
            showClose: true,
            type: 'error'
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        grouping: true,
        showClose: true,
        message: '删除已取消'
      })
    })
}
// 添加
const handleAdd = (type: string) => {
  handleState.value = 'add'
  operationType.value = type
  dialogFormVisible.value = true
  dialogTitle.value = '添加知识库'
}
// 跳转
const jump = (data: any, buttonType: string) => {
  if (buttonType === '知识图谱')
    router.push({
      path: '/knowledge/graph',
      query: {
        graphId: data.rowData.id,
        graphName: data.rowData.graphName,
        featureReleaseStatus: 1
      }
    })
  if (buttonType === '进入图谱知识库')
    router.push({ path: '/knowledge/character', query: { graphId: data.rowData.id } })
  if (buttonType === '进入知识库')
    router.push({
      path: '/knowledge/knowledgeBase',
      query: { graphId: data.rowData.id, graphName: data.rowData.graphName }
    })
  if (buttonType === '节点维护')
    router.push({
      path: '/knowledge/nodeMaintenance',
      query: { graphId: data.rowData.id, graphName: data.rowData.graphName }
    })
  if (buttonType === '碎片化提取')
    router.push({
      path: '/knowledge/extraction',
      query: { graphId: data.rowData.id, graphName: data.rowData.graphName }
    })
}
// 导入
const handleImport = () => {
  importFormRef.value.open()
}
const handleLog = () => {
  graphLogRef.value.open()
}
const bookAdd = () => {
  booksRef.value.open()
}
// 分页：pageSize 改变时会触发
const handleSizeChange = (val: number) => {
  tableModule.pageSize = val
  getTableData()
}
// 分页：currentPage 改变时会触发
const handleCurrentChange = (val: number) => {
  tableModule.currentPage = val
  getTableData()
}
const columns: Column<object>[] = [
  {
    key: 'graphName',
    title: '知识库名称',
    dataKey: 'graphName',
    width: 150,
    align: 'center',
    cellRenderer: ({ cellData: graphName }) => <div>{graphName}</div>
  },
  {
    key: 'graphType',
    title: '知识库类型',
    dataKey: 'graphType',
    width: 100,
    align: 'center',
    cellRenderer: ({ cellData: graphType }) => <div>{graphType}</div>
  },
  {
    key: 'graphIntro',
    title: '知识库简介',
    dataKey: 'graphIntro',
    width: 150,
    align: 'center',
    cellRenderer: ({ cellData: graphIntro }) => <div>{graphIntro}</div>
  },
  {
    key: '',
    title: '图书资源',
    dataKey: '',
    width: 100,
    align: 'center'
    // cellRenderer: ({ cellData: graphName }) => <div>{graphName}</div>,
  },
  {
    key: 'createTime',
    title: '创建时间',
    dataKey: 'createTime',
    width: 200,
    align: 'center'
    // cellRenderer: ({ cellData: createTime }) => (
    //   <el-tooltip content={dayjs(createTime).format("YYYY/MM/DD")}>
    //     {<span class="flex items-center">{dayjs(createTime).format("YYYY/MM/DD")}</span>}
    //   </el-tooltip>
    // ),
  },
  {
    key: 'operations',
    title: '操作',
    cellRenderer: (data) => (
      <>
        <el-button onClick={edit.bind(this, 'edit', data)} type="success" size="small">
          修改
        </el-button>
        <el-button
          v-show={data.rowData.graphType === '图谱知识库'}
          onClick={jump.bind(this, data, '节点维护')}
          type="primary"
          size="small"
        >
          节点维护
        </el-button>
        <el-button
          v-show={data.rowData.graphType === '知识库'}
          onClick={jump.bind(this, data, '进入知识库')}
          type="primary"
          size="small"
        >
          进入知识库
        </el-button>
        <el-button
          v-show={data.rowData.graphType === '图谱知识库'}
          onClick={jump.bind(this, data, '进入图谱知识库')}
          type="primary"
          size="small"
        >
          进入图谱知识库
        </el-button>
        <el-button
          v-show={data.rowData.graphType === '图谱知识库'}
          onClick={jump.bind(this, data, '知识图谱')}
          type="primary"
          size="small"
        >
          知识图谱
        </el-button>
        <el-button
          v-show={data.rowData.graphType === '图谱知识库'}
          onClick={jump.bind(this, data, '碎片化提取')}
          type="primary"
          size="small"
        >
          碎片化提取
        </el-button>
        <el-button
          v-show={data.rowData.graphType === '图谱知识库'}
          onClick={handleValidate.bind(this, data)}
          type="primary"
          size="small"
        >
          图谱关系闭环验证
        </el-button>
        <el-button onClick={deleteFcn.bind(this, data)} type="danger" size="small">
          删除
        </el-button>
      </>
    ),
    width: 650,
    align: 'center'
  }
]
const columnsBooks: Column<object>[] = [
  // {
  //   key: 'selection',
  //   width: 50,
  //   cellRenderer: ({ rowData }) => {
  //     const onChange = (value: CheckboxValueType) => (rowData.checked = value)
  //     return <SelectionCell value={rowData.checked} onChange={onChange} />
  //   },
  //   headerCellRenderer: () => {
  //     const _data = unref(tableModule.tableData)
  //     const onChange = (value: CheckboxValueType) =>
  //     (tableModule.tableData.checked = _data.map((row) => {
  //       row.checked = value
  //       return row
  //     }))
  //     const allSelected = _data.every((row) => row.checked)
  //     const containsChecked = _data.some((row) => row.checked)
  //     return (
  //       <SelectionCell
  //         value={allSelected}
  //         intermediate={containsChecked && !allSelected}
  //         onChange={onChange}
  //       />
  //     )
  //   },
  //   first: true,
  //   second: true,
  //   third: true,
  // },
  {
    key: 'id',
    title: '编号',
    dataKey: 'id',
    width: 50,
    align: 'center',
    cellRenderer: ({ cellData: id }) => <div>{id}</div>
  },
  {
    key: 'fn_cover',
    title: '封面',
    dataKey: 'fn_cover',
    width: 100,
    align: 'center',
    cellRenderer: (data) => (
      <>
        <img
          v-show={data.rowData.fn_cover.length}
          src={data.rowData.fn_cover[0]?.url}
          height={50}
        />
        <el-icon v-show={!data.rowData.fn_cover.length} size="25">
          <Picture />
        </el-icon>
      </>
    )
  },
  {
    key: 'fn_title',
    title: '书名',
    dataKey: 'fn_title',
    width: 200,
    align: 'center',
    cellRenderer: ({ cellData: fn_title }) => <div>{fn_title}</div>
  },
  {
    key: 'fn_isbn',
    title: 'ISBN',
    dataKey: 'fn_isbn',
    width: 200,
    align: 'center',
    cellRenderer: ({ cellData: fn_isbn }) => <div>{fn_isbn}</div>
  },
  {
    key: 'fn_publishername',
    title: '出版社',
    dataKey: 'fn_publishername',
    width: 100,
    align: 'center',
    cellRenderer: ({ cellData: fn_publishername }) => <div>{fn_publishername}</div>
  },
  {
    key: 'create_time',
    title: '创建时间',
    dataKey: 'create_time',
    width: 100,
    align: 'center'
  }
]
</script>
<style lang="scss" scoped>
.area {
  .search {
    .el-form-item {
      margin: 0 32px 0 0;

      a {
        text-decoration: none;
      }
    }
  }
}

.font-color-red {
  color: red;
}

// 弹窗表单组件样式
// .demo-form-inline .el-input {
//   --el-input-width: 230px !important;
// }

// .demo-form-inline .el-select {
//   --el-select-width: 230px !important;
// }

// 上传组件样式
::v-deep(.avatar-uploader .avatar) {
  width: 178px;
  height: 178px;
  display: block;
}

::v-deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

::v-deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
